package org.example.strategy;

import java.io.*;
import java.util.LinkedList;

public class LoadFileStrategy implements EditorStrategy {

    private String filePath;

    private String fileName;

    private LinkedList<String> fileContent;

    public LinkedList<String> getFileContent() {
        return fileContent;
    }

    public String getFileName() {
        return fileName;
    }

    public LoadFileStrategy(String filePath){
        this.filePath = filePath;
        this.fileContent = new LinkedList<>();
    }
    @Override
    public void performAction() {
//        System.out.println("hello this is load file command!");
        load();
    }

    private boolean load(){
        File file = new File(filePath);
        if (file.exists()){
            System.out.println("Loading file from:" + filePath);
            // 将editor中的文件路径切换到新加载的文件
            try(BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
                String line;
                while ((line = reader.readLine()) != null ){
                    fileContent.add(line);
                }
                this.fileName = file.getName();
                System.out.println("File loaded successfully!");
            }catch (Exception e) {
                System.out.println("File loading failure!");
                e.printStackTrace();
                return false;
            }
            return true;
        }
        else {
            try {
                if (file.createNewFile()){
                    System.out.println("New file created:" + filePath);
                    // 将editor中的文件路径切换到新加载的文件
                    this.fileName = file.getName();
                    return true;
                }else {
                    System.out.println("Failed to create a new file:" + filePath);
                    return false;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
    }
}
